package com.itheima.d6_threadhomework0910.num2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CopyRunnable implements Runnable{
    private Punishment punishment;
    public CopyRunnable(Punishment punishment){
        this.punishment = punishment;
    }

    private final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        lock.lock();
        //得到当前线程对象的名称
        String name = Thread.currentThread().getName();
        int leftcount = punishment.getLeftCount();
        //定义count 表示抄写的次数
        int count = 0;

        String copyWord = punishment.getCopyWord();
       try{
           for (int i = 0; i < 100; i++){
               //判断
               leftcount--;
               if(leftcount >= 0) {
                   System.out.println(name + "线程-抄写一遍" + copyWord + "两人总共还剩" + leftcount + "次");
                   punishment.setCount(leftcount);
                   count++;
               }else{
                   break;
               }
           }
           //输出每个线程抄写的次数
           System.out.println(name + "线程-一共抄写了" + count + "次");
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           lock.unlock();

       }


    }
}
